/*
 * Copyright Konstantin Triger <kostat@gmail.com> 
 * 
 * This file is part of Jaque 2 JPA - JAva QUEry 2 JPA library <http://code.google.com/p/jaque/>.
 * 
 * Jaque is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Jaque is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package jaque.jpa;

import jaque.expressions.Expression;

final class SubqueryRemover extends BaseDbExpressionVisitor {

	public static final SubqueryRemover Instance = new SubqueryRemover();

	private SubqueryRemover() {
	}

	@Override
	public Expression visit(SelectExpression e) {
		// return (select.From is SelectExpression || select.From is
		// TableExpression)
		// && (IsSimpleProjection(select) || IsNameMapProjection(select))
		// && !select.IsDistinct
		// && select.Take == null
		// && select.Skip == null
		// && select.Where == null
		// && (select.OrderBy == null || select.OrderBy.Count == 0)
		// && (select.GroupBy == null || select.GroupBy.Count == 0);
		e = (SelectExpression) super.visit(e);
		if (e.getFrom().getExpressionType() == DbExpressionType.Select
				&& !e.isDistinct() && e.getWhere() == null
				&& (e.getOrderBy() == null || e.getOrderBy().size() == 0)
				&& (e.getGroupBy() == null || e.getGroupBy().size() == 0)) {
			SelectExpression from = (SelectExpression) e.getFrom();
			e = new SelectExpression(from.getFrom(), e.getSelector(), from
					.getWhere(), from.getOrderBy(), from.getGroupBy(), from
					.isDistinct());
		}

		return e;
	}
}
